import React, { Component, Suspense, Fragment } from 'react';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { ChromePicker } from 'react-color';
import { connect } from 'dva';
import PageLoading from '@/components/PageLoading';
import { FormattedMessage } from 'umi-plugin-react/locale';
import {
  Row,
  Col,
  Card,
  Icon,
  Tooltip,
  Form,
  Button,
  Input,
  Upload,
  message,
  Radio,
  Spin,
  Switch,
} from 'antd';
import Editor from '@/utils/Editor';
import styles from './index.less';
import imgURL from '../../../assets/accessSettings/icon-a.png';
import LogoimgURL from '../../../assets/accessSettings/icon-头像.png';
import khmrimgURL from '../../../assets/accessSettings/icon-机器人.png';
import AND from '@/assets/icons/AND.png';
import IOS from '@/assets/icons/IOS.png';
import js2 from '@/assets/account/accessSettings/js.png';
import sj2 from '@/assets/account/accessSettings/sj2.png';
import fuzhi from '@/assets/account/accessSettings/fuzhi.png';
import qdbuttom from '@/assets/account/robotSetup/qdbuttom.png';
import qxbuttom from '@/assets/account/robotSetup/qxbuttom.png';

const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const MyIcon = Icon.createFromIconfontCN({
  scriptUrl: '//at.alicdn.com/t/font_1131883_fqf69hupewt.js', // 在 iconfont.cn 上生成
});
const { TextArea } = Input;
class AppAccess extends Component {
  constructor() {
    super();
    this.state = {
      yuyhc: '1', // 语音合成
      yuysran: '1', // 语音输入按钮
      color: '#19c3f3',
      displayColorPicker: false,
      logoa: 'http://www.chatbot.cn/qizhi-client-img/1.png',
      logob: 'http://www.chatbot.cn/qizhi-client-img/2.png',
      logoc: 'http://www.chatbot.cn/qizhi-client-img/3.png',
      entranceWebStyle: '', // 入口图标样式 电脑端
      entranceH5Style: '', // 入口图标样式 移动端
      ckbt: '',
      ckys: '',
      jqrkfName: '',
      // 参数结结束
      imageUrld: null,
      imageUrle: null,
      index: null,
      indextwo: null,
      color: '#19c3f3 ',
      // displayColorPicker: false,
      loading: false,
      loadingA: false,
      loadingB: false,
      valueA: '1',
      valueB: '1',
      valueC: '1',
      ckdxSize: '1',
      mrckdxweb: '1',
      mrckdxydd: '1',
      commonProblemList: [{ name: '', item: '' }],
      pdxs: true,
      content: '',
      spinning: false,
      valueMax: false,
      valueMaxa:false
    };
  }

  componentDidMount() {
    const { dispatch } = this.props;
    this.suax();
  }

  handleChangeComplete = color => {
    console.log(color.hex);
    this.setState({ color: color.hex });
  };

  // ----------- 窗口颜色-----------------------
  handleClick = () => {
    this.setState({ displayColorPicker: !this.state.displayColorPicker });
  };

  handleClose = () => {
    this.setState({ displayColorPicker: false });
  };

  // ----------------客户默认头像----------
  // ----------------客户默认头像----------
  getBase64 = (img, callback) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
  };

  beforeUpload = file => {
    console.log(file);
    const isJPG = file.type;
    const isLt2M = file.size / 1024 / 1024 < 1;
    if (!isLt2M) {
      message.error('Image must smaller than 2MB!');
    }
    return isJPG && isLt2M;
  };

  handleChangeA = info => {
    console.log(info);
    if (info.file.status === 'uploading') {
      this.setState({ loading: true });
      return;
    }
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      this.getBase64(info.file.originFileObj, imageUrla =>
        this.setState({
          imageUrla,
          loading: false,
          logob: info.file.response.url,
        })
      );
    }
  };
  // ------------- 解决状态--------------------

  // ------------- 机器人默认头像--------------
  handleChangeB = info => {
    console.log(info);
    if (info.file.status === 'uploading') {
      this.setState({ loadingA: true });
      return;
    }
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      this.getBase64(info.file.originFileObj, imageUrlb =>
        this.setState({
          imageUrlb,
          loadingA: false,
          logoc: info.file.response.url,
        })
      );
    }
  };

  copy = () => {
    let text = document.getElementById('biao1');
    if (document.body.createTextRange) {
      var range = document.body.createTextRange();
      range.moveToElementText(text);
      range.select();
    } else if (window.getSelection) {
      let selection = window.getSelection();
      let range = document.createRange();
      range.selectNodeContents(text);
      selection.removeAllRanges();
      selection.addRange(range);
    }
    document.execCommand('Copy');
    message.success('复制成功！');
  };

  rktbonChangea = e => {
    console.log(`switch to ${e}`);
    if (e === true) {
      this.setState({
        yuysran: '2',
        valueMaxa: e,
      });
    }
    if (e === false) {
      this.setState({
        yuysran: '1',
        valueMaxa: e,
      });
    }
  };

  rktbonChange = e => {
    console.log(`switch to ${e}`);
    if (e === true) {
      this.setState({
        yuyhc: '2',
        valueMax: e,
      });
    }
    if (e === false) {
      this.setState({
        yuyhc: '1',
        valueMax: e,
      });
    }
  };

  // eslint-disable-next-line react/sort-comp
  render() {
    const popover = {
      position: 'absolute',
      zIndex: '2',
    };
    const gbcolor = {
      background: this.state.color,
    };
    const cover = {
      position: 'fixed',
      top: '0px',
      right: '0px',
      bottom: '0px',
      left: '0px',
    };
    const body = '</body>';
    const { getFieldDecorator } = this.props.form;
    const FormItemLayont = {
      labelCol: {
        sm: 24,
        md: 5,
        lg: 3,
      },
      wrapperCol: {
        sm: 24,
        md: 19,
        lg: 20,
      },
    };
    // 客服头像
    const uploadButton = (
      <img style={{ width: 51, height: 51, borderRadius: '50%' }} src={this.state.logob} />
    );
    // 机器人头像
    const uploadButtona = (
      <img style={{ width: 51, height: 51, borderRadius: '50%' }} src={this.state.logoc} />
    );
    const imageUrla = this.state.imageUrla;
    const imageUrlb = this.state.imageUrlb;
    const imageUrlc = this.state.imageUrlc;
    return (
      <div>
        <Spin spinning={this.state.spinning}>
          <img src={sj2} />
          <span style={{ fontSize: 24, color: '#4a90e2', marginLeft: 30 }}>APP接入说明</span>
          <img style={{ marginLeft: 50, marginBottom: 10 }} src={js2} />
          <div style={{ height: 30 }} />
          <span className={styles.titlep} style={{ marginLeft: 112 }}>
            APPKEY
          </span>
          <div className={styles.borzdy} />
          <p style={{ margin: '22px 0px 22px 112px', color: '#9B9B9B' }}>
            请将以下代码添加到你网站的HTML源代码中，放在标签{body}之前，即可实现接入
          </p>
          <div className={styles.textTitleDeV}>
            <div className={styles.textTitle} id="biao1">
              7fe6fb533e4c4521e7b3d5027748d06d
            </div>
          </div>
          <img onClick={this.copy} style={{ margin: '30px 0px 20px 106px' }} src={fuzhi} />
          <div style={{ height: 30 }} />
          <span style={{ marginLeft: 112 }} className={styles.titlep}>
            <span>APP接入设置</span>
          </span>
          <div className={styles.borzdy} />
          <div style={{ height: 30 }} />
          <div>
            <div style={{ marginLeft: 112 }}>
              <Form className="zdyfroma" layout="horizontal">
                <FormItem className='zdyswer' label="语音合成" {...FormItemLayont}>
                  {getFieldDecorator('yuyhc', {
                    initialValue: this.state.yuyhc,
                  })(
                    <div>
                      <Switch
                        className={styles.zdySwitch}
                        defaultChecked
                        onChange={this.rktbonChange}
                        checked={this.state.valueMax}
                      />
                      <span
                        style={{
                          marginLeft: 10,
                          color: '#1D1D1D',
                          position: 'relative',
                          top: 2,
                        }}
                      >
                        {this.state.valueMax ? '关闭' : '开启'}
                      </span>
                    </div>
                    // <RadioGroup>
                    //   <Radio value='1'>开启</Radio>
                    //   <Radio value='2'>关闭</Radio>
                    // </RadioGroup>
                  )}
                </FormItem>
                <FormItem className='zdyswer' label="语音输入按钮" {...FormItemLayont}>
                  {getFieldDecorator('yuysran', {
                    initialValue: this.state.yuysran,
                  })(
                    <div>
                      <Switch
                        className={styles.zdySwitch}
                        defaultChecked
                        onChange={this.rktbonChangea}
                        checked={this.state.valueMaxa}
                      />
                      <span
                        style={{
                          marginLeft: 10,
                          color: '#1D1D1D',
                          position: 'relative',
                          top: 2,
                        }}
                      >
                        {this.state.valueMaxa ? '关闭' : '开启'}
                      </span>
                    </div>
                    // <RadioGroup>
                    //   <Radio value='1'>显示</Radio>
                    //   <Radio value='2'>隐藏</Radio>
                    // </RadioGroup>
                  )}
                </FormItem>
                <FormItem label="窗口颜色" {...FormItemLayont}>
                  {getFieldDecorator('ckcolor', {
                    initialValue: this.state.color,
                  })(
                    <div className={styles.flexColor}>
                      <div style={gbcolor} className={styles.colorzj} onClick={this.handleClick} />
                      <span>{this.state.color}</span>
                      {this.state.displayColorPicker ? (
                        <div style={popover}>
                          <div style={cover} onClick={this.handleClose} />
                          <ChromePicker
                            color={this.state.color}
                            onChangeComplete={this.handleChangeComplete}
                          />
                        </div>
                      ) : null}
                    </div>
                  )}
                </FormItem>
                <FormItem className="Uploadlg" label="客户默认头像" {...FormItemLayont}>
                  <Upload
                    name="avatar"
                    listType="picture"
                    className="avatar-uploader"
                    showUploadList={false}
                    action="/cloud/res/upload"
                    beforeUpload={this.beforeUpload}
                    onChange={this.handleChangeA}
                  >
                    <div className={styles.xzwj}>
                      {imageUrla ? (
                        <img
                          style={{ width: 51, height: 51, borderRadius: '50%' }}
                          src={imageUrla}
                          alt="avatar"
                        />
                      ) : (
                        uploadButton
                      )}
                      <Button style={{ marginLeft: 10 }} size="small">
                        选择文件
                      </Button>
                    </div>
                  </Upload>
                  <p style={{ fontSize: 10, color: '#99a8b7', marginBottom: 0 }}>
                    标题栏左侧Logo图，大小不超过1MB,推荐图片尺寸50*50
                  </p>
                </FormItem>
                <FormItem label="机器人客服头像" {...FormItemLayont}>
                  <Upload
                    name="customersFace"
                    listType="picture"
                    className="avatar-uploader"
                    showUploadList={false}
                    action="/cloud/res/upload"
                    beforeUpload={this.beforeUpload}
                    onChange={this.handleChangeB}
                  >
                    <div className={styles.xzwj}>
                      {imageUrlb ? (
                        <img
                          style={{ width: 51, height: 51, borderRadius: '50%'}}
                          src={imageUrlb}
                          alt="customersFace"
                        />
                      ) : (
                        uploadButtona
                      )}
                      <Button style={{ marginLeft: 10 }} size="small">
                        选择文件
                      </Button>
                    </div>
                  </Upload>
                  <p style={{ fontSize: 10, color: '#99a8b7', marginBottom: 0 }}>
                    标题栏左侧Logo图，大小不超过1MB,推荐图片尺寸50*50
                  </p>
                </FormItem>
                <FormItem label="机器人客服名称" {...FormItemLayont}>
                  {getFieldDecorator('jqrkfName', {
                    initialValue: this.state.jqrkfName,
                  })(<Input style={{ width: 280 }} />)}
                </FormItem>
              </Form>
            </div>
          </div>
          <div className={styles.webSetBotton} />
          <div style={{ margin: '24px 0px 24px 0px' }}>
            <div className={styles.flexcenm}>
              <div>
                {/*<img onClick={this.quxiao} src={qxbuttom} style={{ marginRight: 50 }} />*/}
                <img onClick={this.baocun} src={qdbuttom} />
              </div>
            </div>
            {/* <Button onClick={this.quxiao} style={{ marginRight: 10 }}>取消</Button>
            <Button onClick={this.baocun} type='primary'>保存</Button> */}
          </div>
        </Spin>
      </div>
    );
  }

  baocun = () => {
    let userInfo = this.props.form.getFieldsValue(); // 获取数据
    console.log(userInfo);

    const { color, logob, logoc } = this.state;
    this.props.form.validateFields((err, values) => {
      // 校验方法
      console.log(userInfo);
      const { dispatch, currentUser } = this.props;
      this.reqRef = requestAnimationFrame(() => {
        dispatch({
          type: 'accessSettings/fetchf',
          payload: {
            voiceSynthesisFlag: Number(userInfo.yuyhc),
            voiceShowFlag: Number(userInfo.yuysran),
            winColor: color,
            robotHeadImg:  this.state.logob,
            userHeadImg:  this.state.logoc,
            robotName: userInfo.jqrkfName,
          },
          callback: res => {
            console.log('列表数据', res);
            if (res.code === 0) {
              message.success(`${res.msg}`);
              this.suax();
            }
          },
        });
      });
    });
  };

  suax = () => {
    this.setState({ spinning: true });
    const { dispatch, currentUser } = this.props;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'accessSettings/fetchg',
        payload: {},
        callback: res => {
          console.log('获取网站接入信息', res);

          if (res.userHeadImg !== null) {
            this.setState({ logob: res.userHeadImg });
          }

          if (res.robotHeadImg !== null) {
            this.setState({ logoc: res.robotHeadImg });
          }
          if (res.voiceSynthesisFlag == 2) {
            this.setState({ valueMax: true });
          }

          if (res.voiceSynthesisFlag == 1) {
            this.setState({ valueMax: false });
          }

          if (res.voiceShowFlag == 2) {
            this.setState({ valueMaxa: true });
          }

          if (res.voiceShowFlag == 1) {
            this.setState({ valueMaxa: false });
          }

          this.setState({
            yuyhc: res.voiceSynthesisFlag?String(res.voiceSynthesisFlag):'1',
            // color: res.winColor,
            color: res.winColor ? res.winColor : '#11cbff',
            // logob: res.userHeadImg,
            // logoc: res.robotHeadImg,
            voiceShowFlag: String(res.voiceShowFlag),
            yuysran:res.voiceShowFlag?String(res.voiceShowFlag):'1',
            jqrkfName: res.robotName,
            spinning: false,
          });
        },
      });
    });
  };

  quxiao = () => {
    this.props.form.setFields({ jqrkfName: '' });
    this.props.form.setFields({ yuyhc: '' });
    this.props.form.setFields({ yuysran: '' });
    this.suax();
  };
}
export default connect(({ user }) => ({
  // 全局数据
  currentUser: user.currentUser,
}))(Form.create()(AppAccess));
